package com.base.system.jpa.repository;

import com.base.system.jpa.entity.JpaMenu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

public interface MenuRepository extends JpaRepository<JpaMenu, Long>, JpaSpecificationExecutor<JpaMenu> {
    Optional<JpaMenu> findFirstByUrlAndIdNot(String url, Long id);

    Optional<JpaMenu> findFirstByUrl(String url);

    List<JpaMenu> findAllByIdIn(List<Long> ids);

    /**
     * 只获取同级的，不去查询子数据
     *
     * @param ids
     * @return
     */
    @Query(value = "select * from menu  where id in (:ids)", nativeQuery = true)
    List<JpaMenu> findAllByIdInIsSibling(@Param("ids") List<Long> ids);

    @Query("select jm from JpaMenu jm where jm.parent.id is null or trim(jm.parent.id)='' order by jm.sortCode desc ")
    List<JpaMenu> findAllByParentIdNotNull();

    @Query("select jm from JpaMenu jm where jm.parent.id =:parentId")
    List<JpaMenu> findAllByParentId(@Param("parentId") Long parentId);

    @Query(value = "SELECT\n" +
            "menu.id,\n" +
            "menu.icon,\n" +
            "menu.is_disable,\n" +
            "menu.name_zh,\n" +
            "menu.sort_code,\n" +
            "menu.url,\n" +
            "menu.parent_id,\n" +
            "menu.file_path\n" +
            "FROM\n" +
            "menu\n" +
            "WHERE menu.id=:id or menu.parent_id=:id", nativeQuery = true)
    List<JpaMenu> findAllById(@Param("id") Long id);

    @Modifying
    @Transactional
    @Query("update JpaMenu m " +
            "set " +
            "m.icon=:#{#menu.icon}," +
            "m.isDisable=:#{#menu.isDisable}," +
            "m.nameZh=:#{#menu.nameZh}," +
            "m.sortCode=:#{#menu.sortCode}," +
            "m.url=:#{#menu.url}," +
            "m.parent=:#{#menu.parent}," +
            "m.filePath=:#{#menu.filePath} " +
            "where m.id=:#{#menu.id}")
    void update(@Param("menu") JpaMenu menu);
}
